<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: dark)"><meta name="generator" content="Hexo 5.2.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/img/16x16.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/img/32x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/img/16x16.png">
  <link rel="mask-icon" href="/img/logo.png" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://unpkg.com/@fortawesome/fontawesome-free@6.3.0/css/all.min.css" integrity="sha256-/4UQcSmErDzPCMAiuOiWPVVsNN2s3ZY/NsmXNcj0IFc=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://unpkg.com/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css" integrity="sha256-Vzbj7sDDS/woiFS3uNKo8eIuni59rjyNGtXfstRzStA=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"lirifa.github.io","root":"/","images":"/images","scheme":"Mist","darkmode":true,"version":"8.15.0","exturl":false,"sidebar":{"position":"right","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"mac"},"bookmark":{"enable":true,"color":"#2bb5d4","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"livere","storage":true,"lazyload":false,"nav":null,"activeClass":"livere"},"stickytabs":false,"motion":{"enable":false,"async":false,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="我们将这种事件流向分为三个阶段：捕获阶段，目标阶段，冒泡阶段。">
<meta property="og:type" content="article">
<meta property="og:title" content="DOM事件流">
<meta property="og:url" content="https://lirifa.github.io/DOM%E4%BA%8B%E4%BB%B6%E6%B5%81.html">
<meta property="og:site_name" content="Rafa&#39;s Blog">
<meta property="og:description" content="我们将这种事件流向分为三个阶段：捕获阶段，目标阶段，冒泡阶段。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://s3.ax1x.com/2020/11/20/DQyEwV.png">
<meta property="og:image" content="https://s3.ax1x.com/2020/11/20/DQglOs.png">
<meta property="og:image" content="https://s3.ax1x.com/2020/11/20/DQgI0I.png">
<meta property="og:image" content="https://s3.ax1x.com/2020/11/20/DQ2yuj.png">
<meta property="og:image" content="https://s3.ax1x.com/2020/11/20/DQR1I0.png">
<meta property="og:image" content="https://s3.ax1x.com/2020/11/26/D0peJK.png">
<meta property="article:published_time" content="2020-11-20T09:16:59.000Z">
<meta property="article:modified_time" content="2020-12-15T13:26:56.260Z">
<meta property="article:author" content="Rafa">
<meta property="article:tag" content="前端">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://s3.ax1x.com/2020/11/20/DQyEwV.png">


<link rel="canonical" href="https://lirifa.github.io/DOM%E4%BA%8B%E4%BB%B6%E6%B5%81.html">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://lirifa.github.io/DOM%E4%BA%8B%E4%BB%B6%E6%B5%81.html","path":"DOM事件流.html","title":"DOM事件流"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>DOM事件流 | Rafa's Blog</title>
  

  <script src="/js/third-party/analytics/baidu-analytics.js"></script>
  <script async src="https://hm.baidu.com/hm.js?e65b95711a0ae7fa2a5d53e3186cff24"></script>







  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">Rafa's Blog</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">角落</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li><li class="menu-item menu-item-留言"><a href="/guestbook/" rel="section"><i class="fa fa-book fa-fw"></i>留言</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E4%BB%80%E4%B9%88%E6%98%AFDOM%E4%BA%8B%E4%BB%B6%E6%B5%81"><span class="nav-text">1.什么是DOM事件流</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E4%BA%8B%E4%BB%B6%E5%86%92%E6%B3%A1%E5%92%8C%E4%BA%8B%E4%BB%B6%E6%8D%95%E8%8E%B7"><span class="nav-text">2.事件冒泡和事件捕获</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E4%BA%8B%E4%BB%B6%E5%86%92%E6%B3%A1%E4%B8%BE%E4%BE%8B"><span class="nav-text">3.事件冒泡举例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-%E4%BA%8B%E4%BB%B6%E6%8D%95%E8%8E%B7%E4%B8%BE%E4%BE%8B"><span class="nav-text">4.事件捕获举例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-%E4%BA%8B%E4%BB%B6%E6%8D%95%E8%8E%B7VS%E4%BA%8B%E4%BB%B6%E5%86%92%E6%B3%A1"><span class="nav-text">5.事件捕获VS事件冒泡</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-%E4%BA%8B%E4%BB%B6%E4%BB%A3%E7%90%86%EF%BC%88%E4%BA%8B%E4%BB%B6%E5%A7%94%E6%89%98%EF%BC%89"><span class="nav-text">6.事件代理（事件委托）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#7-%E6%80%BB%E7%BB%93"><span class="nav-text">7.总结</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Rafa"
      src="https://avatars.githubusercontent.com/u/44889418?v=4">
  <p class="site-author-name" itemprop="name">Rafa</p>
  <div class="site-description" itemprop="description">角落</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">10</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">3</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/lirifa" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;lirifa" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:rafa_im@163.com" title="E-Mail → mailto:rafa_im@163.com" rel="noopener me" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://lirifa.github.io/DOM%E4%BA%8B%E4%BB%B6%E6%B5%81.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="https://avatars.githubusercontent.com/u/44889418?v=4">
      <meta itemprop="name" content="Rafa">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Rafa's Blog">
      <meta itemprop="description" content="角落">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="DOM事件流 | Rafa's Blog">
      <meta itemprop="description" content="我们将这种事件流向分为三个阶段：捕获阶段，目标阶段，冒泡阶段。">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          DOM事件流
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2020-11-20 17:16:59" itemprop="dateCreated datePublished" datetime="2020-11-20T17:16:59+08:00">2020-11-20</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2020-12-15 21:26:56" itemprop="dateModified" datetime="2020-12-15T21:26:56+08:00">2020-12-15</time>
    </span>

  
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>5.8k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>5 分钟</span>
    </span>
</div>

            <div class="post-description">我们将这种事件流向分为三个阶段：捕获阶段，目标阶段，冒泡阶段。</div>
        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h2 id="1-什么是DOM事件流"><a href="#1-什么是DOM事件流" class="headerlink" title="1.什么是DOM事件流"></a>1.什么是DOM事件流</h2><p>话不多说，先附上W3C链接：<a target="_blank" rel="noopener" href="https://www.w3.org/TR/DOM-Level-3-Events/#event-flow">https://www.w3.org/TR/DOM-Level-3-Events/#event-flow</a><br><img src="https://s3.ax1x.com/2020/11/20/DQyEwV.png" alt="www.w3.org/TR/DOM-Leve…"><br>上图是W3C标准的DOM事件流模型图，从图中可以看出，元素事件响应在DOM树中是从顶层的Window开始“流向”目标元素（），然后又从目标元素“流向”顶层的Window。</p>
<p>通常，我们将这种事件流向分为三个阶段：<strong>捕获阶段</strong>，<strong>目标阶段</strong>，<strong>冒泡阶段</strong>。</p>
<ul>
<li>捕获阶段是指事件响应从最外层的Window开始，逐级向内层前进，直到具体事件目标元素。在捕获阶段，不会处理响应元素注册的冒泡事件。</li>
<li> 目标阶段指触发事件的最底层的元素，如上图中的。</li>
<li> 冒泡阶段与捕获阶段相反，事件的响应是从最底层开始一层一层往外传递到最外层的Window。</li>
</ul>
<p>现在，我们就可以知道，DOM事件流的三个阶段是先捕获阶段，然后是目标阶段，最后才是冒泡阶段。我们时常面试所说的先捕获后冒泡也由此而来。事件代理就是利用事件冒泡或事件捕获的机制把一系列的内层元素事件绑定到外层元素。</p>
<h2 id="2-事件冒泡和事件捕获"><a href="#2-事件冒泡和事件捕获" class="headerlink" title="2.事件冒泡和事件捕获"></a>2.事件冒泡和事件捕获</h2><p>实际操作中，我们可以通过 element.addEventListener() 设置一个元素的事件模型为冒泡事件或者捕获事件。</p>
<p>先来看一下 addEventListener 函数的语法： </p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">element.addEventListener(type, listener, useCapture)</span><br></pre></td></tr></table></figure>
<ul>
<li>type<br>监听事件类型的字符串  </li>
<li>listener<br>事件监听回调函数，即事件触发后要处理的函数  </li>
<li>useCapture<br>默认值false，表示事件冒泡；设为true时，表示事件捕获</li>
</ul>
<h2 id="3-事件冒泡举例"><a href="#3-事件冒泡举例" class="headerlink" title="3.事件冒泡举例"></a>3.事件冒泡举例</h2><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;a&quot;</span> <span class="attr">style</span>=<span class="string">&quot;width: 300px; height: 300px;background-color: red;&quot;</span>&gt;</span></span><br><span class="line">    a</span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;b&quot;</span> <span class="attr">style</span>=<span class="string">&quot;width: 200px; height: 200px;background-color: yellow;&quot;</span>&gt;</span></span><br><span class="line">        b</span><br><span class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;c&quot;</span> <span class="attr">style</span>=<span class="string">&quot;width: 100px; height: 100px;background-color: #2b9ab4;&quot;</span>&gt;</span></span><br><span class="line">            c</span><br><span class="line">        <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript"><span class="keyword">var</span> a = <span class="built_in">document</span>.getElementById(<span class="string">&#x27;a&#x27;</span>)</span></span><br><span class="line"><span class="javascript"><span class="keyword">var</span> b = <span class="built_in">document</span>.getElementById(<span class="string">&#x27;b&#x27;</span>)</span></span><br><span class="line"><span class="javascript"><span class="keyword">var</span> c = <span class="built_in">document</span>.getElementById(<span class="string">&#x27;c&#x27;</span>)</span></span><br><span class="line"><span class="javascript"><span class="comment">//注册冒泡事件监听器</span></span></span><br><span class="line"><span class="javascript">a.addEventListener(<span class="string">&#x27;click&#x27;</span>, <span class="function">() =&gt;</span> &#123;<span class="built_in">console</span>.log(<span class="string">&quot;捕获a&quot;</span>)&#125;)</span></span><br><span class="line"><span class="javascript">b.addEventListener(<span class="string">&#x27;click&#x27;</span>, <span class="function">() =&gt;</span> &#123;<span class="built_in">console</span>.log(<span class="string">&#x27;捕获b&#x27;</span>)&#125;)</span></span><br><span class="line"><span class="javascript">c.addEventListener(<span class="string">&#x27;click&#x27;</span>, <span class="function">() =&gt;</span> &#123;<span class="built_in">console</span>.log(<span class="string">&quot;捕获c&quot;</span>)&#125;)</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>当我们点击c时，执行结果如下：</p>
<p><img src="https://s3.ax1x.com/2020/11/20/DQglOs.png" alt="执行结果"></p>
<p>冒泡事件的执行顺序为：c -&gt; b -&gt; a</p>
<h2 id="4-事件捕获举例"><a href="#4-事件捕获举例" class="headerlink" title="4.事件捕获举例"></a>4.事件捕获举例</h2><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;a&quot;</span> <span class="attr">style</span>=<span class="string">&quot;width: 300px; height: 300px;background-color: red;&quot;</span>&gt;</span></span><br><span class="line">    a</span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;b&quot;</span> <span class="attr">style</span>=<span class="string">&quot;width: 200px; height: 200px;background-color: yellow;&quot;</span>&gt;</span></span><br><span class="line">        b</span><br><span class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;c&quot;</span> <span class="attr">style</span>=<span class="string">&quot;width: 100px; height: 100px;background-color: #2b9ab4;&quot;</span>&gt;</span></span><br><span class="line">            c</span><br><span class="line">        <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript"><span class="keyword">var</span> a = <span class="built_in">document</span>.getElementById(<span class="string">&#x27;a&#x27;</span>)</span></span><br><span class="line"><span class="javascript"><span class="keyword">var</span> b = <span class="built_in">document</span>.getElementById(<span class="string">&#x27;b&#x27;</span>)</span></span><br><span class="line"><span class="javascript"><span class="keyword">var</span> c = <span class="built_in">document</span>.getElementById(<span class="string">&#x27;c&#x27;</span>)</span></span><br><span class="line"><span class="javascript"><span class="comment">//注册捕获事件监听器</span></span></span><br><span class="line"><span class="javascript">a.addEventListener(<span class="string">&#x27;click&#x27;</span>, <span class="function">() =&gt;</span> &#123;<span class="built_in">console</span>.log(<span class="string">&quot;捕获a&quot;</span>)&#125;, <span class="literal">true</span>)</span></span><br><span class="line"><span class="javascript">b.addEventListener(<span class="string">&#x27;click&#x27;</span>, <span class="function">() =&gt;</span> &#123;<span class="built_in">console</span>.log(<span class="string">&#x27;捕获b&#x27;</span>)&#125;, <span class="literal">true</span>)</span></span><br><span class="line"><span class="javascript">c.addEventListener(<span class="string">&#x27;click&#x27;</span>, <span class="function">() =&gt;</span> &#123;<span class="built_in">console</span>.log(<span class="string">&quot;捕获c&quot;</span>)&#125;, <span class="literal">true</span>)</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>当我们点击c时，运行结果如下：<br><img src="https://s3.ax1x.com/2020/11/20/DQgI0I.png" alt="执行结果"><br>捕获事件的执行顺序为：a -&gt; b -&gt; c</p>
<h2 id="5-事件捕获VS事件冒泡"><a href="#5-事件捕获VS事件冒泡" class="headerlink" title="5.事件捕获VS事件冒泡"></a>5.事件捕获VS事件冒泡</h2><p>我们将上述的代码a,b,c三个元素都注册捕获和冒泡事件，并以元素c作为触发事件的主体，即事件流中的目标阶段。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;a&quot;</span> <span class="attr">style</span>=<span class="string">&quot;width: 300px; height: 300px;background-color: red;&quot;</span>&gt;</span></span><br><span class="line">    a</span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;b&quot;</span> <span class="attr">style</span>=<span class="string">&quot;width: 200px; height: 200px;background-color: yellow;&quot;</span>&gt;</span></span><br><span class="line">        b</span><br><span class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;c&quot;</span> <span class="attr">style</span>=<span class="string">&quot;width: 100px; height: 100px;background-color: #2b9ab4;&quot;</span>&gt;</span></span><br><span class="line">            c</span><br><span class="line">        <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript"><span class="keyword">var</span> a = <span class="built_in">document</span>.getElementById(<span class="string">&#x27;a&#x27;</span>)</span></span><br><span class="line"><span class="javascript"><span class="keyword">var</span> b = <span class="built_in">document</span>.getElementById(<span class="string">&#x27;b&#x27;</span>)</span></span><br><span class="line"><span class="javascript"><span class="keyword">var</span> c = <span class="built_in">document</span>.getElementById(<span class="string">&#x27;c&#x27;</span>)</span></span><br><span class="line"><span class="javascript"><span class="comment">//注册冒泡事件监听器</span></span></span><br><span class="line"><span class="javascript">a.addEventListener(<span class="string">&#x27;click&#x27;</span>, <span class="function">() =&gt;</span> &#123;<span class="built_in">console</span>.log(<span class="string">&quot;冒泡a&quot;</span>)&#125;)</span></span><br><span class="line"><span class="javascript">b.addEventListener(<span class="string">&#x27;click&#x27;</span>, <span class="function">() =&gt;</span> &#123;<span class="built_in">console</span>.log(<span class="string">&#x27;冒泡b&#x27;</span>)&#125;)</span></span><br><span class="line"><span class="javascript">c.addEventListener(<span class="string">&#x27;click&#x27;</span>, <span class="function">() =&gt;</span> &#123;<span class="built_in">console</span>.log(<span class="string">&quot;冒泡c&quot;</span>)&#125;)</span></span><br><span class="line"><span class="javascript"><span class="comment">//注册捕获事件监听器</span></span></span><br><span class="line"><span class="javascript">a.addEventListener(<span class="string">&#x27;click&#x27;</span>, <span class="function">() =&gt;</span> &#123;<span class="built_in">console</span>.log(<span class="string">&quot;捕获a&quot;</span>)&#125;, <span class="literal">true</span>)</span></span><br><span class="line"><span class="javascript">b.addEventListener(<span class="string">&#x27;click&#x27;</span>, <span class="function">() =&gt;</span> &#123;<span class="built_in">console</span>.log(<span class="string">&#x27;捕获b&#x27;</span>)&#125;, <span class="literal">true</span>)</span></span><br><span class="line"><span class="javascript">c.addEventListener(<span class="string">&#x27;click&#x27;</span>, <span class="function">() =&gt;</span> &#123;<span class="built_in">console</span>.log(<span class="string">&quot;捕获c&quot;</span>)&#125;, <span class="literal">true</span>)</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>a,b,c三个元素都是先注册冒泡事件再注册捕获事件，当我们点击c时，执行结果又是如何？请看下图。<br><img src="https://s3.ax1x.com/2020/11/20/DQ2yuj.png" alt="执行结果"><br>从执行结果可以看到，a,b两个元素的事件响应都是先捕获后冒泡的，但对于触发事件的目标元素c，事件的响应并没有遵循先捕获后冒泡的规则</p>
<p>这是为什么？</p>
<p>因为<strong>目标元素是事件触发主体处于事件流中的目标阶段，处理事件的顺序是根据注册顺序来执行的。</strong></p>
<p>我们将上图中c元素的事件注册调换一下顺序</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;a&quot;</span> <span class="attr">style</span>=<span class="string">&quot;width: 300px; height: 300px;background-color: red;&quot;</span>&gt;</span></span><br><span class="line">    a</span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;b&quot;</span> <span class="attr">style</span>=<span class="string">&quot;width: 200px; height: 200px;background-color: yellow;&quot;</span>&gt;</span></span><br><span class="line">        b</span><br><span class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;c&quot;</span> <span class="attr">style</span>=<span class="string">&quot;width: 100px; height: 100px;background-color: #2b9ab4;&quot;</span>&gt;</span></span><br><span class="line">            c</span><br><span class="line">        <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript"><span class="keyword">var</span> a = <span class="built_in">document</span>.getElementById(<span class="string">&#x27;a&#x27;</span>)</span></span><br><span class="line"><span class="javascript"><span class="keyword">var</span> b = <span class="built_in">document</span>.getElementById(<span class="string">&#x27;b&#x27;</span>)</span></span><br><span class="line"><span class="javascript"><span class="keyword">var</span> c = <span class="built_in">document</span>.getElementById(<span class="string">&#x27;c&#x27;</span>)</span></span><br><span class="line"><span class="javascript"><span class="comment">//注册冒泡事件监听器</span></span></span><br><span class="line"><span class="javascript">a.addEventListener(<span class="string">&#x27;click&#x27;</span>, <span class="function">() =&gt;</span> &#123;<span class="built_in">console</span>.log(<span class="string">&quot;冒泡a&quot;</span>)&#125;)</span></span><br><span class="line"><span class="javascript">b.addEventListener(<span class="string">&#x27;click&#x27;</span>, <span class="function">() =&gt;</span> &#123;<span class="built_in">console</span>.log(<span class="string">&#x27;冒泡b&#x27;</span>)&#125;)</span></span><br><span class="line"></span><br><span class="line"><span class="javascript"><span class="comment">// 事件注册调换顺序</span></span></span><br><span class="line"><span class="javascript">c.addEventListener(<span class="string">&#x27;click&#x27;</span>, <span class="function">() =&gt;</span> &#123;<span class="built_in">console</span>.log(<span class="string">&quot;捕获c&quot;</span>)&#125;, <span class="literal">true</span>)</span></span><br><span class="line"><span class="javascript">c.addEventListener(<span class="string">&#x27;click&#x27;</span>, <span class="function">() =&gt;</span> &#123;<span class="built_in">console</span>.log(<span class="string">&quot;冒泡c&quot;</span>)&#125;)</span></span><br><span class="line"></span><br><span class="line"><span class="javascript"><span class="comment">//注册捕获事件监听器</span></span></span><br><span class="line"><span class="javascript">a.addEventListener(<span class="string">&#x27;click&#x27;</span>, <span class="function">() =&gt;</span> &#123;<span class="built_in">console</span>.log(<span class="string">&quot;捕获a&quot;</span>)&#125;, <span class="literal">true</span>)</span></span><br><span class="line"><span class="javascript">b.addEventListener(<span class="string">&#x27;click&#x27;</span>, <span class="function">() =&gt;</span> &#123;<span class="built_in">console</span>.log(<span class="string">&#x27;捕获b&#x27;</span>)&#125;, <span class="literal">true</span>)</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>执行结果：<br><img src="https://s3.ax1x.com/2020/11/20/DQR1I0.png" alt="执行结果"><br>对于非目标元素，如果我们要先执行冒泡事件再执行捕获事件，我们可以在注册监听器时通过暂缓执行捕获事件，等冒泡事件执行完之后，在执行捕获事件。</p>
<h2 id="6-事件代理（事件委托）"><a href="#6-事件代理（事件委托）" class="headerlink" title="6.事件代理（事件委托）"></a>6.事件代理（事件委托）</h2><p>我们知道了事件冒泡和事件捕获的原理，那么对于事件委托就比较容易理解了。<br>重复一遍</p>
<blockquote>
<p>事件代理就是利用事件冒泡或事件捕获的机制把一系列的内层元素事件绑定到外层元素。<br>至于为什么通常我们说事件代理是利用事件冒泡的机制来实现的，只是大家习以为常而已。</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">ul</span> <span class="attr">id</span>=<span class="string">&quot;item-list&quot;</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">li</span>&gt;</span>item1<span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">li</span>&gt;</span>item2<span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">li</span>&gt;</span>item3<span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">li</span>&gt;</span>item4<span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>对于上述的列表元素，我们希望将用户点击了哪个item打印出来，通常我们可以给每个item注册点击事件监听器，但是需要对每个元素进行事件监听器的注册；但是通过事件代理，我们可以将多个事件监听器减少为一个，这样就减少代码的重复编写了。</p>
<p>利用事件冒泡或事件捕获实现事件代理：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> items = <span class="built_in">document</span>.getElementById(<span class="string">&#x27;item-list&#x27;</span>);</span><br><span class="line"><span class="comment">//事件捕获实现事件代理</span></span><br><span class="line">items.addEventListener(<span class="string">&#x27;click&#x27;</span>, <span class="function">(<span class="params">e</span>) =&gt;</span> &#123;<span class="built_in">console</span>.log(<span class="string">&#x27;捕获：click &#x27;</span>,e.target.innerHTML)&#125;, <span class="literal">true</span>);</span><br><span class="line"><span class="comment">//事件冒泡实现事件代理</span></span><br><span class="line">items.addEventListener(<span class="string">&#x27;click&#x27;</span>, <span class="function">(<span class="params">e</span>) =&gt;</span> &#123;<span class="built_in">console</span>.log(<span class="string">&#x27;冒泡：click &#x27;</span>,e.target.innerHTML)&#125;, <span class="literal">false</span>);</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>当点击列表中的item时，执行结果如下：<br><img src="https://s3.ax1x.com/2020/11/26/D0peJK.png" alt="执行结果"></p>
<p><strong>因此，事件代理既可以通过事件冒泡来实现，也可以通过事件捕获来实现。</strong></p>
<h2 id="7-总结"><a href="#7-总结" class="headerlink" title="7.总结"></a>7.总结</h2><p>以上的东西总结起来就是有以下几点：</p>
<ul>
<li>DOM事件流有3个阶段：捕获阶段，目标阶段，冒泡阶段；三个阶段的顺序为：捕获阶段——目标阶段——冒泡阶段；</li>
<li>对于非目标阶段的元素，事件响应执行顺序遵循先捕获后冒泡的原则；通过暂缓执行捕获事件，可以达到先冒泡后捕获的效果；</li>
<li>对于目标元素，事件响应执行顺序根据的事件的执行顺序执行；</li>
<li>事件捕获是从顶层的Window逐层向内执行，事件冒泡则相反；</li>
<li>事件委托（事件代理）是根据事件冒泡或事件捕获的机制来实现的。</li>
</ul>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/%E5%89%8D%E7%AB%AF/" rel="tag"><i class="fa fa-tag"></i> 前端</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/WebSocket%E5%8D%8F%E8%AE%AE%E4%BB%8B%E7%BB%8D.html" rel="prev" title="WebSocket协议介绍">
                  <i class="fa fa-chevron-left"></i> WebSocket协议介绍
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/H5-video%E5%BC%80%E5%8F%91%E9%97%AE%E9%A2%98%E5%8F%8A%E7%9B%B8%E5%85%B3%E7%9F%A5%E8%AF%86%E7%82%B9.html" rel="next" title="H5 video开发问题及相关知识点">
                  H5 video开发问题及相关知识点 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






    <div class="comments" id="lv-container" data-id="city" data-uid="MTAyMC82MDk1Ni8zNzQyNg=="></div>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2025</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Rafa</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>站点总字数：</span>
    <span title="站点总字数">38k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">34 分钟</span>
  </span>
</div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>
  <a role="button" class="book-mark-link book-mark-link-fixed"></a>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script size="100" alpha="0.3" zIndex="-1" src="https://unpkg.com/ribbon.js@1.0.2/dist/ribbon.min.js"></script>
  <script src="https://unpkg.com/animejs@3.2.1/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://unpkg.com/jquery@3.6.3/dist/jquery.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
  <script src="https://unpkg.com/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js" integrity="sha256-yt2kYMy0w8AbtF89WXb2P1rfjcP/HTHLT7097U8Y5b8=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script><script src="/js/bookmark.js"></script>

  <script src="https://unpkg.com/hexo-generator-searchdb@1.4.1/dist/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>



  <script src="/js/third-party/fancybox.js"></script>


  




<script src="/js/third-party/comments/livere.js"></script>

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","model":{"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"left","width":160,"height":280},"mobile":{"show":false},"react":{"opacityDefault":1,"opacityOnHover":1},"log":false,"tagMode":false});</script></body>
</html>
